﻿using FileSharing.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FileSharing.Controllers
{
    [HandleError]
    public class FilesController : Controller
    {
        //
        // GET: /Files/               
        public ActionResult Index(string path)
        {
            ActionResult result = null;
            IList<Exception> exceptions = null;

            var model = ModelHelper.ToModel(path, (e) => exceptions = e);

            if (exceptions != null
                && exceptions.Count > 0)
                model.Message = string.Format("There were {0} error{1} in processing this request", exceptions.Count, exceptions.Count <= 1 ? "" : "s");

            if (model.Exists
                && model.FileType == Models.PathType.File)
            {
                this.Response.BufferOutput = false;
                this.AddResponseHeaders(model.FullPath);

                result = new FileStreamResult(System.IO.File.OpenRead(model.FullPath), System.Net.Mime.MediaTypeNames.Application.Octet);
            }
            else
            {
                result = this.View(model);
            }

            return result ?? new EmptyResult();

        }

        private void AddResponseHeaders(string filePath)
        {
            var fileInfo = new System.IO.FileInfo(filePath);

            var disposition = new System.Net.Mime.ContentDisposition();
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;
            disposition.FileName = fileInfo.Name;
            disposition.CreationDate = fileInfo.CreationTime;
            disposition.ReadDate = fileInfo.LastAccessTime;
            disposition.ModificationDate = fileInfo.LastWriteTime;
            disposition.Size = fileInfo.Length;
            disposition.FileName = fileInfo.Name;

            var response = this.HttpContext.Response;
            response.Clear();
            response.AddHeader("Content-Length", fileInfo.Length.ToString());
            response.AddHeader("Content-Type", System.Net.Mime.MediaTypeNames.Application.Octet);
            response.AddHeader("Content-Disposition", disposition.ToString());
            response.BufferOutput = false;
        }

        [HttpPost]
        public ActionResult Upload(/*params HttpPostedFileBase[] files */)
        {
            string targetPath = this.Request.Form["targetPath"] ?? string.Empty;
            var files = this.Request.Files;

            if (files != null
                && files.Count > 0
                && !string.IsNullOrWhiteSpace(targetPath)
                && System.IO.Directory.Exists(targetPath))
            {
                bool overwriteOriginal = string.Equals("overwriteOriginal", this.Request.Form["overwriteOriginal"]);

                for (int i = 0; i < files.Count; i++)
                {
                    var file = files[i];

                    string filePath = System.IO.Path.Combine(targetPath, file.FileName);

                    if (!System.IO.File.Exists(filePath) || overwriteOriginal)
                    {
                        file.SaveAs(filePath);
                    }
                }

            }
            return this.RedirectToAction("index", "files", new { path = targetPath });
        }

        [HttpDelete]
        public ActionResult Delete()
        {
            return new EmptyResult();
        }

    }
}
